move ( char_id, x_dir, y_dir ) : moves a character to a neighbor ground, after checking the destination ground, the distance and the PA cost (updated). The x_dir and y_dir parameters could be -1, 0 or 1. Returns 1 if the parameters are wrong, 2 if destination ground is undefined, 3 if the character doesn t have enough PA. And 0 if everything is OK.

CREATE FUNCTION move( INTEGER, INTEGER, INTEGER ) RETURNS INTEGER AS '

DECLARE 

id_char ALIAS FOR $1;
x_dir   ALIAS FOR $2;
y_dir   ALIAS FOR $3;

x_dest  INTEGER;
y_dest  INTEGER;

pos_dest POINT;
pos_char POINT;
pa_char  INTEGER;

ground_dest_type INTEGER;
ground_dest_pa   INTEGER;

new_pa_char INTEGER;

BEGIN
	SELECT char_pos FROM characters WHERE char_id = id_char INTO pos_char;
	
	IF (x_dir >= -1 AND x_dir <= 1) THEN x_dest = pos_char[0] + x_dir; END IF;
	IF (y_dir >= -1 AND y_dir <= 1) THEN y_dest = pos_char[1] + y_dir; END IF;
	
	pos_dest := POINT ( x_dest, y_dest );
	IF (pos_dest ~= pos_char) THEN
		RETURN 1;
	END IF;
	
	SELECT type_id FROM grounds WHERE ( ground_pos ~= pos_dest ) INTO ground_dest_type;
	IF (ground_dest_type = 0) THEN
		RETURN 2;
	END IF;

	SELECT type_move_pa FROM ground_types WHERE type_id = ground_dest_type INTO ground_dest_pa;
	
	SELECT char_pa FROM characters WHERE char_id = id_char INTO pa_char;
	
	new_pa_char := pa_char - ground_dest_pa;
	
	IF ( new_pa_char > 0 ) THEN
		UPDATE characters SET char_pos = pos_dest, char_pa = new_pa_char WHERE char_id = id_char;
		RETURN 0;
	END IF;
	RETURN 3;
END; '
LANGUAGE plpgsql;